import requests
from lxml import etree
import os

class myPlay(object):

    def getHtml(self):
        print("进入视频获取方法")
        url = "https://ibaotu.com/shipin/"

        headers = {
            'User-Agent': 'Mozilla/5.0 (Window Nt 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36'
        }

        rep = requests.get(url, headers=headers)
        domTree = etree.HTML(rep.text)
        res = domTree.xpath('//li')[5]

        # 获取视频的名称和所在地址
        nameList = res.xpath('(//span[@class="video-title"]/text())')
        srcList = res.xpath('(//div[@class="video-play"]/video/@src)')

        for name, src in zip(nameList, srcList):
            print("视频标题：" + name + "访问地址：" + src)
            self.downMP4(name, src)

    def downMP4(self, name, src):
        print("进入视频下载方法")
        mp4Path = "d:/Desktop/mp4/" + name + ".mp4"

        try:
            if not os.path.exists("d:/Desktop/mp4/"):
                os.mkdir("d:/Desktop/mp4/")
            if not os.path.exists(mp4Path):
                content = requests.get("http:" + src).content
                with open(mp4Path, "wb") as f:
                    f.write(content)
                    f.close()
                    print("抓取视频成功")
        except Exception as e:
            print("抓取视频失败，原因是：" + e.args)